// JavaScript Document

var loggedIn = false;
var isAdmin = false;
var alwaysShowAccount = false;

var createURL = "createaccount.py";
var accountURL = "accountreturn.py";
var sendInfoURL = "editaccount.py";
var loginURL = "login.py";
var logoutURL = "logout.py";

var seenDataShareMessage = false;
var dataShareAnswer = "false";


function login_prefetch() {
	$.mobile.loadPage( "create.html" );
	$.mobile.loadPage( "share.html" );
	$.mobile.loadPage( "account_created.html" );
}

function setHomePage() {

	// set the log in button
	if(loggedIn) {
		$('#login_button').attr("style", "display:none;");
		$('#logout_button').attr("style", "display:block;");
	}
	else {
		$('#login_button').attr("style", "display:block;");
		$('#logout_button').attr("style", "display:none;");
	}
	
	// show or hide the account icon
	if(loggedIn || alwaysShowAccount) {
		$('#account_icon').attr("style", "display:block;");
	}
	else {
		$('#account_icon').attr("style", "display:none;");
	}
	
	// show or hide the admin icon
	if(isAdmin) {
		$('#admin_icon').attr("style", "display:block;");
	}
	else {
		$('#admin_icon').attr("style", "display:none;");
	}
}

function login() {

	var username = $('#login_user_name').val();
	var password = $('#login_password_temp').val();
	var deviceid = $('#deviceid').val();
	
	if (username == "admin" && password == "password") {
		isAdmin = true;
		$.mobile.changePage("../../index.html");
		return;
	}
	
	var url = urlThrive + loginURL;
	var args = new String("");
	
	// add the encrypted password
	var encrypt = encryptPassword(username, password);
	args = args.concat("&user_name=", username);
	args = args.concat("&password=", encrypt);
	args = args.concat("&device_id=", TEST_DEVICE);
	
	if (DEBUG_ALERTS) {
		alert(url + "?" + args);
	}
	
	removePopup();
	$.mobile.silentScroll(0);
	showPopup('&nbsp;&nbsp;Sending...&nbsp;&nbsp;');
	
	jQuery.ajax({
		timeout: 8000,
		type: "GET",
		url: url,
		data: args,
		dataType: "text",
		crossDomain: true,

		//success: function (msg) {
		success: function(data, textStatus, jqXHR){

			var message = data.split(":");
			
			if( message.length < 3) {
				$.mobile.silentScroll(0);
				removePopup();
				showPopup('Server error, please try again later.'); 
				return;
			}
			
			var error = parseInt(message[0]);
			
			// success! redirect to login page
			if (error == 0){
				removePopup();
				loggedIn = true;
				USER_NAME = username;
				$.mobile.changePage("../../index.html", {transition: "slideup", reverse: true});	
			}
			
			// error! display message
			else if (error == -1) {
				$.mobile.silentScroll(0);
				removePopup();
				showPopup(message[1]); 
			}
			
			// error! display message and move to form element
			else if (error == -2 ) {
				$.mobile.silentScroll(0);
				removePopup();
				showPopup(message[1]); 
			}
		},
		error: function(jqXHR, textStatus, errorThrown){

			$.mobile.silentScroll(0);
			removePopup();
			showPopup("Network Error. Please try again later."); 
		}
	}); 
}

function logout() {
	
	var username = USER_NAME;
	var deviceid = TEST_DEVICE;
	
	var url = urlThrive + logoutURL;
	var args = new String("");
	
	// add the encrypted password
	args = args.concat("user_name=", username);
	args = args.concat("&device_id=", deviceid);
	
	if (DEBUG_ALERTS) {
		alert(url + "?" + args);
	}
	
	jQuery.ajax({
		timeout: 8000,
		type: "GET",
		url: url,
		data: args,
		dataType: "text",
		crossDomain: true,

		//success: function (msg) {
		success: function(data, textStatus, jqXHR){

			loggedIn = false;
			DATA_SHARE = "false";
			BIRTHDATE = "";
			GRADE = "";
			SEX = "";
			ETHNICITY = "";
			PARENT1 = "";
			PARENT2 = "";
			TOUCHSCREEN = "";
			USE = "";
			setHomePage();
		},
		error: function(jqXHR, textStatus, errorThrown){

			loggedIn = false;
			DATA_SHARE = "false";
			BIRTHDATE = "";
			GRADE = "";
			SEX = "";
			ETHNICITY = "";
			PARENT1 = "";
			PARENT2 = "";
			TOUCHSCREEN = "";
			USE = "";
			setHomePage();
		}
	}); 
}

function clearLoginForm() {
	$('#login_user_name').val("");
	$('#login_password_temp').val("");
}

function clearCreateForm() {
	
	seenDataShareMessage = false;
	$('#user_name').val("");
	$('#password_temp').val("");
	$('#confirm').val("");
	$('#parent1').val("");
	$('#parent2').val("");
	$('#not-sure-0').attr("checked", false);
	$('#not-sure-0').trigger("change");
	$('#not-sure-1').attr("checked", false);
	$('#not-sure-1').trigger("change");
}

function clearCreateForm_nodata() {
	
	seenDataShareMessage = false;
	$('#user_name_nodata').val("");
	$('#password_temp_nodata').val("");
	$('#confirm_nodata').val("");
}

function sendAccountInfo() {
	
	var username = USER_NAME;
	var deviceid = TEST_DEVICE;
	
	var url = urlThrive + sendInfoURL;
	var args = $('#account_form').serialize();
	
	// add the username and deviceid
	args = args.concat("&user_name=", username);
	args = args.concat("&device_id=", deviceid);
	
	// concatenate the date
	var birthdate = getAccountBirthdate();
	args = args.concat("&birthdate=", birthdate);
	
	if (DEBUG_ALERTS) {
		alert(url + "?" + args);
	}
	
	jQuery.ajax({
		timeout: 8000,
		type: "GET",
		url: url,
		data: args,
		dataType: "text",
		crossDomain: true,

		//success: function (msg) {
		success: function(data, textStatus, jqXHR){

			var message = data.split(":");
			
			if( message.length < 3) {
				$.mobile.silentScroll(0);
				removePopup();
				showPopup('Server error, please try again later.'); 
				return;
			}
			
			var success = parseInt(message[0]);
			
			if (success == 0) {
				
			}
			// error!
			else if (success == -1) {
				$.mobile.silentScroll(0);
				removePopup();
				showPopup(message[1]); 
			}
		},
		error: function(jqXHR, textStatus, errorThrown){

			$.mobile.silentScroll(0);
			removePopup();
			showPopup("Failed to save your changes, please try again later."); 
		}
	}); 
}

function getAccountInfo() {

	var username = USER_NAME;
	var deviceid = TEST_DEVICE;
	
	var url = urlThrive + accountURL;
	var args = new String("");
	
	// add the username and deviceid
	args = args.concat("user_name=", username);
	args = args.concat("&device_id=", deviceid);
	
	if (DEBUG_ALERTS) {
		alert(url + "?" + args);
	}
	
	jQuery.ajax({
		timeout: 8000,
		type: "GET",
		url: url,
		data: args,
		dataType: "text",
		crossDomain: true,

		//success: function (msg) {
		success: function(data, textStatus, jqXHR){

			var message = data.split(":");
			
			if( message.length < 3) {
				$.mobile.silentScroll(0);
				removePopup();
				showPopup('Server error, please try again later.'); 
				return;
			}
			
			var success = parseInt(message[0]);
			
			// error!
			if (success == -1) {
				$.mobile.silentScroll(0);
				removePopup();
				showPopup(message[1]); 
			}
			
			// data share = false
			else if (success == 1) {
				DATA_SHARE = "false";
			}
			
			// data share = true
			else if (success == 2) {
				
				var accountInfo = message[1].split("^");
				
				if (accountInfo.length != 9) {
					
					DATA_SHARE = "false";
					// take them to error explaining server fuckup
					//$.mobile.changePage();
				}
				else {
					
					DATA_SHARE = "true";
					BIRTHDATE = accountInfo[0];
					SEX = accountInfo[1];
					GRADE = accountInfo[2];
					ETHNICITY = accountInfo[3];
					PARENT1 = accountInfo[4];
					PARENT2 = accountInfo[5];
					TOUCHSCREEN = accountInfo[6];
					USE = accountInfo[7];
					fillAccount();
					toggleAccountDemographics();
				}
			}
		},
		error: function(jqXHR, textStatus, errorThrown){

			$.mobile.silentScroll(0);
			removePopup();
			showPopup("Failed to retrieve your information, please try again later."); 
		}
	}); 
}

function fillAccount() {

	$("#title_username").html(USER_NAME);
	$("#account_device_id").val(TEST_DEVICE);
	
	// get the info from already retured from the server
	$("#account_data_share").val(DATA_SHARE);
	$("#account_data_share").trigger("change");
	
	if (DATA_SHARE) {
	
		var birthdate = BIRTHDATE.split("-");
		var year = birthdate[0];
		var month = birthdate[1];
		var day = birthdate[2];
		
		$("#account_year").val(year);
		$("#account_year").trigger("change");
		
		$("#account_month").val(month);
		$("#account_month").trigger("change");
		
		$("#account_day").val(day);
		$("#account_day").trigger("change");
		
		$("#account_sex").val(SEX);
		$("#account_sex").trigger("change");
		
		$("#account_grade").val(GRADE);
		$("#account_grade").trigger("change");
		
		$("#account_ethnicity").val(ETHNICITY);
		$("#account_ethnicity").trigger("change");
		
		if (PARENT1 != "N/A") {
			$("#account_parent1").val(PARENT1);
			$("#account_parent1").trigger("change");
		}
		
		if (PARENT2 != "N/A") {
			$("#account_parent2").val(PARENT2);
			$("#account_parent2").trigger("change");
		}
		
		if (TOUCHSCREEN == "0") {
			TOUCHSCREEN = "false";
		}
		else if (TOUCHSCREEN == "1") {
			TOUCHSCREEN = "true";
		}
		$("#account_touchscreen").val(TOUCHSCREEN);
		$("#account_touchscreen").trigger("change");
		
		$("#account_use").val(USE);
		$("#account_use").trigger("change");
	}
}

function toggleDemographics() {
	
	if ($('#data_share').val() == "true") {
		$('#demographics').attr("style", "display:block;");
	}
	else {
		$('#demographics').attr("style", "display:none;");
	}
}

function toggleAccountDemographics() {
	
	if ($('#account_data_share').val() == "true") {
		$('#account_demographics').attr("style", "display:block;");
	}
	else {
		$('#account_demographics').attr("style", "display:none;");
		
		removePopup();
		showPopup("Warning: not sharing your data will clear all your saved information.");
	}
}

/* Some admin functions */

function changeConnect() {
	
	urlThrive = $('#connect').val();
}

function changeDeviceID() {
	
	if ($('#device_change').val() == "0") {
		TEST_DEVICE = "1234567";
	}
	else if ($('#device_change').val() == "1") {
		TEST_DEVICE = "9999";
	}
	else if ($('#device_change').val() == "2") {
		TEST_DEVICE = "2907456";
	}
	else {
		TEST_DEVICE = "";
	}
}

function changeAlerts() {
	
	if ($('#alerts').val() == "true") {
		DEBUG_ALERTS = true;
	}
	else {
		DEBUG_ALERTS = false;
	}
}

function autoLogin() {
	
	if (!loggedIn) {
		loggedIn = true;
		USER_NAME = "TESTER";
		$.mobile.changePage("../../index.html");
	}
	else {
		alert("first log out");	
	}
}


function toggleToAccount() {
	
	$('#account_data_share').selectmenu('disable');
	$('#account_day').selectmenu('disable');
	$('#account_month').selectmenu('disable');
	$('#account_year').selectmenu('disable');
	$('#account_grade').selectmenu('disable');
	$('#account_sex').selectmenu('disable');
	$('#account_ethnicity').selectmenu('disable');
	$('#account_parent1').textinput('disable');
	$('#account_parent2').textinput('disable');
	$('#account_touchscreen').selectmenu('disable');
	$('#account_use').selectmenu('disable');	

	$("#toggleToEdit").attr("style", "visibility:visible");
	$("#toggleToAccount").attr("style", "visibility:hidden");
}

function toggleToEdit() {
	
	$('#account_data_share').selectmenu('enable');
	$('#account_day').selectmenu('enable');
	$('#account_month').selectmenu('enable');
	$('#account_year').selectmenu('enable');
	$('#account_grade').selectmenu('enable');
	$('#account_sex').selectmenu('enable');
	$('#account_ethnicity').selectmenu('enable');
	$('#account_parent1').textinput('enable');
	$('#account_parent2').textinput('enable');
	$('#account_touchscreen').selectmenu('enable');
	$('#account_use').selectmenu('enable');	

	$("#toggleToEdit").attr("style", "visibility:hidden");
	$("#toggleToAccount").attr("style", "visibility:visible");
}

function toggleParent1() {

	if ($('#not-sure-0').is(':checked'))  {
		$('#parent1').val("");
		$('#parent1').textinput('disable');
	}
	else {
		$('#parent1').textinput('enable');
	}
}

function toggleParent2() {

	if ($('#not-sure-1').is(':checked'))  {
		$('#parent2').val("");
		$('#parent2').textinput('disable');
	}
	else {
		$('#parent2').textinput('enable');
	}
}

function displayDataShareMessage() {
	
	if(!seenDataShareMessage) {
	
		showPopup("You have a decision to make. If you like, you can agree for your all of the information that you enter on the Thrive application to be sent to the creators. If you do so, your information would be associated with an ID number only – not your name. That means it would be very difficult if not impossible for you to be identified. The researchers are interested in looking at questions such as: What are the average mood ratings like for teens when they start using the app and after they have been using it for some time? How do teens’ beliefs about self relate to their moods? What kinds of stories do teens tell about their strengths? If you decide to allow your data to be used for research purposes, you should know that your data will be kept on an encrypted server for 10 years or more. Only researchers directly associated with the Thrive research project will have access to your information.", 1); 
		seenDataShareMessage = true;
	}
}

function encryptPassword(username, password) {
	
	var encrypt = "5" + password + username + "5";
	encrypt = Crypto.SHA1(encrypt);
	
	return encrypt;
}

function verifyPasswordLength() {
	
	var pass1 = $('#password_temp').val();
	pass1 = trim(pass1);
	
	if( pass1.length < 6 ) {
		$.mobile.silentScroll(0);
		removePopup();
		showPopup("Your password must be at least 6 characters long.");
	}
}

function verifyPasswordLength_nodata() {
	
	var pass1 = $('#password_temp_nodata').val();
	pass1 = trim(pass1);
	
	if( pass1.length < 6 ) {
		$.mobile.silentScroll(0);
		removePopup();
		showPopup("Your password must be at least 6 characters long.");
	}
}

function verifyPasswords() {
	
	var pass1 = $('#password_temp').val();
	var pass2 = $('#confirm').val();
	
	pass1 = trim(pass1);
	pass2 = trim(pass2);
	
	if( pass1 != pass2 ) {
		$.mobile.silentScroll(0);
		removePopup();
		showPopup("Your passwords do not match. Please re-enter.");
		return false;
	}
	
	if( pass1.length < 6 ) {
		$.mobile.silentScroll(0);
		removePopup();
		showPopup("Your password must be at least 6 characters long.");
		return false;
	}
	
	return true;
}

function verifyPasswords_nodata() {
	
	var pass1 = $('#password_temp_nodata').val();
	var pass2 = $('#confirm_nodata').val();
	
	pass1 = trim(pass1);
	pass2 = trim(pass2);
	
	if( pass1 != pass2 ) {
		$.mobile.silentScroll(0);
		removePopup();
		showPopup("Your passwords do not match. Please re-enter.");
		return false;
	}
	
	if( pass1.length < 6 ) {
		$.mobile.silentScroll(0);
		removePopup();
		showPopup("Your password must be at least 6 characters long.");
		return false;
	}
	
	return true;
}

function getBirthdate() {
	
	var day = $('#day').val();
	var month = $('#month').val();
	var year = $('#year').val();
	
	var birthdate = new String("");
	birthdate = birthdate.concat(year, "-", month, "-", day);
	
	return birthdate;
}

function getAccountBirthdate() {
	
	var day = $('#account_day').val();
	var month = $('#account_month').val();
	var year = $('#account_year').val();
	
	var birthdate = new String("");
	birthdate = birthdate.concat(year, "-", month, "-", day);
	
	return birthdate;
}

function createAccount() {
	
	// check the provided passwords
	var username = $('#user_name').val();
	var password = $('#password_temp').val();
	
	if ( !verifyPasswords() ) {
		return;	
	}
	$('#password_temp').val("");
	$('#confirm').val("");
	
	var url = urlThrive + createURL;
	var args = $('#create_form').serialize();
	
	// add the encrypted password and data share
	var encrypt = encryptPassword(username, password);
	args = args.concat("&password=", encrypt);
	args = args.concat("&data_share=", dataShareAnswer);
	
	// concatenate the date
	if(dataShareAnswer == "true") {
		var birthdate = getBirthdate();
		args = args.concat("&birthdate=", birthdate);
	}
	
	if (DEBUG_ALERTS) {
		alert(url + "?" + args);
	}
	
	removePopup();
	$.mobile.silentScroll(0);
	showPopup('&nbsp;&nbsp;Sending...&nbsp;&nbsp;');
	
	jQuery.ajax({
		timeout: 8000,
		type: "GET",
		url: url,
		data: args,
		dataType: "text",
		crossDomain: true,

		//success: function (msg) {
		success: function(data, textStatus, jqXHR){

			var message = data.split(":");
			
			if( message.length < 3) {
				$.mobile.silentScroll(0);
				removePopup();
				showPopup('Server error, please try again later.'); 
				return;
			}
			
			var error = parseInt(message[0]);
			
			// success! redirect to login page
			if (error == 0){
				removePopup();
				$.mobile.changePage("account_created.html", {rel: "dialog", transition: "pop"});	
			}
			
			// error! display message
			else if (error == -1) {
				$.mobile.silentScroll(0);
				removePopup();
				showPopup(message[1]); 
			}
			
			// error! display message and move to form element
			else if (error == -2 ) {
				$.mobile.silentScroll(0);
				removePopup();
				showPopup(message[1]); 
			}
		},
		error: function(jqXHR, textStatus, errorThrown){

			$.mobile.silentScroll(0);
			removePopup();
			showPopup("Network Error. Please try again later."); 
		}
	}); 
	
}

function createAccount_nodata() {
	
	// check the provided passwords
	var username = $('#user_name_nodata').val();
	var password = $('#password_temp_nodata').val();
	
	if ( !verifyPasswords_nodata() ) {
		return;	
	}
	$('#password_temp_nodata').val("");
	$('#confirm_nodata').val("");
	
	var url = urlThrive + createURL;
	var args = $('#create_form_nodata').serialize();
	
	// add the encrypted password and data share
	var encrypt = encryptPassword(username, password);
	args = args.concat("&password=", encrypt);
	args = args.concat("&data_share=", dataShareAnswer);
	
	if (DEBUG_ALERTS) {
		alert(url + "?" + args);
	}
	
	removePopup();
	$.mobile.silentScroll(0);
	showPopup('&nbsp;&nbsp;Sending...&nbsp;&nbsp;');
	
	jQuery.ajax({
		timeout: 8000,
		type: "GET",
		url: url,
		data: args,
		dataType: "text",
		crossDomain: true,

		//success: function (msg) {
		success: function(data, textStatus, jqXHR){

			var message = data.split(":");
			
			if( message.length < 3) {
				$.mobile.silentScroll(0);
				removePopup();
				showPopup('Server error, please try again later.'); 
				return;
			}
			
			var error = parseInt(message[0]);
			
			// success! redirect to login page
			if (error == 0){
				removePopup();
				$.mobile.changePage("account_created.html", {rel: "dialog", transition: "pop"});	
			}
			
			// error! display message
			else if (error == -1) {
				$.mobile.silentScroll(0);
				removePopup();
				showPopup(message[1]); 
			}
			
			// error! display message and move to form element
			else if (error == -2 ) {
				$.mobile.silentScroll(0);
				removePopup();
				showPopup(message[1]); 
			}
		},
		error: function(jqXHR, textStatus, errorThrown){

			$.mobile.silentScroll(0);
			removePopup();
			showPopup("Network Error. Please try again later."); 
		}
	}); 
	
}


// Removes leading whitespaces
function ltrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}

// Removes ending whitespaces
function rtrim( value ) {
	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
}

// Removes leading and ending whitespaces
function trim( value ) {
	
	return ltrim(rtrim(value));
}
